package com.basker.pisces.orm.data.meta;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.basker.pisces.core.meta.IDataField;
import com.basker.pisces.orm.data.DataRow;

/**
 * 数据字段的元信息
 *
 * @author hangwen
 */
public class FieldMeta {
    // 字段的查询索引，与查询语句中的字段顺序一致
    private int selectIndex = -1;
    // 关联的数据字段
    private IDataField dataField;
    // 数据库字段名
    private String name;
    // 所属的数据库表名
    private String tableName;
    // 字段在表中的顺序
    private int sort = 0;
    // 注释
    private String comment;

    public FieldMeta(IDataField dataField) {
        Assert.notNull(dataField, "parameter 'dataField' is required");
        Assert.hasText(dataField.getDbFieldName(), "parameter 'dataField.getDbFieldName()' is required");

        this.dataField = dataField;
        this.name = dataField.getDbFieldName();

        String hostTableName = dataField.getHostTableName();
        if (!StringUtils.isEmpty(hostTableName)) {
            this.tableName = hostTableName;
        }

        this.sort = dataField.getSort();
        this.comment = dataField.getDescription();
    }

    /**
     * 获取字段注释
     *
     * @return
     */
    public String getComment() {
        return this.comment;
    }

    /**
     * 获取关联的数据字段
     *
     * @return
     */
    public IDataField getDataField() {
        return dataField;
    }

    /**
     * 数据库字段名
     *
     * @return
     */
    public String getName() {
        return name;
    }

    /**
     * 查询索引，与字段查询语句中的顺序一致
     *
     * @return
     */
    public int getSelectIndex() {
        return selectIndex;
    }

    /**
     * 获取字段在数据表中的顺序
     *
     * @return
     */
    public int getSort() {
        return sort;
    }

    /**
     * 字段所属的数据表表名
     *
     * @return
     */
    public String getTableName() {
        return tableName;
    }

    /**
     * 从resultSet中读取当前字段的值，并赋值给行对象
     *
     * @param row
     * @param rs
     * @throws SQLException
     */
    public void readFieldValue(DataRow row, ResultSet rs) throws SQLException {
        row.setValue(selectIndex, this.getFieldValue(rs));
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public void setSelectIndex(int selectIndex) {
        this.selectIndex = selectIndex;
    }

    @Override
    public String toString() {
        return this.tableName != null ? this.tableName + "." + this.name : this.name;
    }

    /**
     * 从resultSet中读取当前字段的值
     *
     * @param resultSet
     * @return
     * @throws SQLException
     */
    protected Object getFieldValue(ResultSet resultSet) throws SQLException {
        return resultSet.getObject(selectIndex + 1);
    }

    void setTableName(String tableName) {
        this.tableName = tableName;
    }

}
